#Rest 方式与模型进行一次对话
import json

import requests

# 模型地址
url = "http://localhost:11434/api/chat"

# 请求数据
data = {
    "model": "deepseek-r1:1.5b",
    "messages": [{"role": "user", "content": "给我讲一个笑话"}]
}

# 获取相应 pip install requests
response = requests.post(url, json=data, stream=False)

#解析response
if response.status_code == 200:
    full_response = []  # 用于存储完整的回复内容
    # 遍历流式响应
    for line in response.iter_lines():
        if line:
            # 解码该行并解析JSON
            decoded_line = line.decode("utf-8")
            # print(f"接收到的行内容: {decoded_line}")  # 打印每一行的内容
            try:
                result = json.loads(decoded_line)
                # 提取message中的content字段并添加到full_response列表
                content = result.get("message", {}).get("content", "")
                if content:
                    full_response.append(content)
                # 检查done字段的值
                if result.get("done", False):
                    break  # 如果done为true，结束循环
            except json.JSONDecodeError as e:
                print(f"JSON解析错误: {e}")
    # 输出完整的回复内容
    print("生成的文本:", "".join(full_response))
else:
    print("错误:", response.status_code, response.text)

